package com.telit.uav.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.telit.common.constant.RoleCodeConstants;
import com.telit.common.dto.SysUserRolePageDto;
import com.telit.common.entity.PageData;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.JwtTokenUtils;
import com.telit.common.vo.user.Result;
import com.telit.common.vo.user.SysUserShortVo;
import com.telit.uav.dao.CommTeamDao;
import com.telit.uav.dao.CommTeamUserDao;
import com.telit.uav.dto.TeamDTO;
import com.telit.uav.dto.TeamDeleteDTO;
import com.telit.uav.dto.TeamMemberDTO;
import com.telit.uav.entity.CommTeam;
import com.telit.uav.feign.UpmsFeignClient;
import com.telit.uav.service.TeamService;
import com.telit.uav.service.TeamUserService;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Auther amy
 * @Describe
 */
@Service
public class TeamServiceImpl implements TeamService {

    @Autowired
    private CommTeamDao commTeamDao;

    @Autowired
    private CommTeamUserDao commTeamUserDao;

    @Autowired
    private TeamUserService teamUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UpmsFeignClient upmsFeignClient;

    @Override
    public List<TeamDTO> listNoPage(String teamName, String teamType) {
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
      /*  List<TeamDTO> list = commTeamDao.list(teamName, teamType);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(teamDTO -> {
                SysUserDetailVo vo = userInfoService.getUserInfo(teamDTO.getLeaderId());
                teamDTO.setLeaderName(vo == null ? null : vo.getRealName());
            });
        }
        return list;*/
        List<TeamDTO> list = commTeamDao.list(teamName, teamType);
        if (!CollectionUtils.isEmpty(list)) {
            final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(list.stream().map(TeamDTO::getLeaderId).collect(Collectors.toList()));
            list.forEach(teamDTO -> {
                final String realName = ObjectUtil.defaultIfNull(idNameMapping.get(teamDTO.getLeaderId()), StrUtil.EMPTY);
                teamDTO.setLeaderName(realName);
            });
        }
        return list;
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------end
    }

    @Override
    public void remove(TeamDeleteDTO teamDeleteDTO) {
        commTeamDao.deleteById(Convert.toLong(teamDeleteDTO.getId()));
    }

    @Override
    @Transactional
    public int add(TeamDTO sysTeamDTO) {
        // 判断名称是否重复
        CommTeam checkName = selectByName(sysTeamDTO.getTeamName());
        if (checkName != null) {
            throw new ForestBaseException("队伍名称不能重复");
        }

        // 更改基本信息
        CommTeam sysTeamEntity = new CommTeam();
        BeanUtils.copyProperties(sysTeamDTO, sysTeamEntity);
        sysTeamEntity.setCreateTime(new Date());
        sysTeamEntity.setCreateUser(JwtTokenUtils.getRealName());
        int count = commTeamDao.insert(sysTeamEntity);
        // 新增人员(将队长id也添加进集合)
        Set<TeamMemberDTO> memberList = prepareLeaderId(sysTeamDTO);
        teamUserService.insertBatchUserTeam(sysTeamEntity.getId(), memberList);
        return count;
    }

    @Override
    @Transactional
    public int update(TeamDTO sysTeamDTO) {
        // 判断名称是否重复
        CommTeam checkName = selectByName(sysTeamDTO.getTeamName());
        if (checkName != null && !sysTeamDTO.getId().equals(checkName.getId())) {
            throw new ForestBaseException("队伍名称不能重复");
        }
        // 更改基本信息
        CommTeam sysTeamEntity = new CommTeam();
        BeanUtils.copyProperties(sysTeamDTO, sysTeamEntity);
        sysTeamEntity.setUpdateTime(new Date());
        sysTeamEntity.setUpdateUser(JwtTokenUtils.getRealName());

        // 更改队伍成员信息
        // 删除原有成员信息
        commTeamUserDao.deleteBatchByUserIdAndTeamId(sysTeamDTO.getId(), null);

        // 新增现有的成员的信息
        // 新增人员(将队长id也添加进集合)
        Set<TeamMemberDTO> memberList = prepareLeaderId(sysTeamDTO);
        teamUserService.insertBatchUserTeam(sysTeamDTO.getId(), memberList);
        return commTeamDao.updateById(sysTeamEntity);
    }

    /**
     * 将队长添加进队伍成员集合
     *
     * @param sysTeamDTO
     */
    private Set<TeamMemberDTO> prepareLeaderId(TeamDTO sysTeamDTO) {
        Set<TeamMemberDTO> memberList = sysTeamDTO.getTeamMemberList();
        if (sysTeamDTO.getLeaderId() != null) {
            if (CollectionUtils.isEmpty(memberList)) {
                memberList = new HashSet<>();
            }
            memberList.add(new TeamMemberDTO(sysTeamDTO.getLeaderId(), sysTeamDTO.getLeaderName()));
        }
        return memberList;
    }

    @Override
    public TeamDTO detail(Long id) {
        CommTeam sysTeamEntity = commTeamDao.selectById(id);
        if (sysTeamEntity != null) {
            TeamDTO sysTeamDTO = new TeamDTO();
            BeanUtils.copyProperties(sysTeamEntity, sysTeamDTO);
            // 返回成员id让前端回显
            sysTeamDTO.setMemberIdList(commTeamUserDao.selectUserIdsByTeamId(id));
            sysTeamDTO.setLeaderInfo(userInfoService.getUserInfo(sysTeamEntity.getLeaderId()));
            return sysTeamDTO;
        }
        return null;
    }

    @Override
    public PageData memberDetailByPage(Integer current, Integer size, Long teamId, String queryName) {
        // 分页查询用户队伍
        IPage<Long> iPage = new Page<>(current, size);
        iPage = commTeamUserDao.listByCondition(iPage, teamId, queryName);

        //获取到分页之后的用户id
        List<Long> userIds = iPage.getRecords();
        if (CollectionUtils.isEmpty(userIds)) {
            return new PageData(0, current, size, null);
        }
        List<MicroSysUserAllInfoVo> userList = userInfoService.queryUserInfoByIds(userIds);
        return new PageData((int) iPage.getTotal(), current, size, userList);
    }

    @Override
    public CommTeam selectByName(String name) {
        QueryWrapper<CommTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("team_name", name);
        return commTeamDao.selectOne(queryWrapper);
    }

    @Override
    public List<SysUserShortVo> excludeTeamUser(Long teamId) {
        List<SysUserShortVo> list = uavUserList();

        // 查询所有在队伍中的用户id
        Set<Long> teamUserIdList = commTeamUserDao.selectUserIds(teamId);

        // 根据列表过滤不在团队中的用户
        if (!CollectionUtils.isEmpty(list)) {
            list = list.stream().filter(userVo -> !teamUserIdList.contains(userVo.getId())).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<SysUserShortVo> uavUserList() {
        SysUserRolePageDto sysUserRolePageDto = new SysUserRolePageDto();
        sysUserRolePageDto.setRoleCode(RoleCodeConstants.ROLE_CODE_UAV_USER);
        Result<List<SysUserShortVo>> resultList = upmsFeignClient.getListForRole(sysUserRolePageDto);
        if (resultList == null || resultList.getData() == null) {
            return null;
        }

        List<SysUserShortVo> list = JSON.parseArray(JSON.toJSONString(resultList.getData()), SysUserShortVo.class);
        return list;
    }

    @Override
    public CommTeam selectByUserId(Long userId, String teamType) {
        return commTeamDao.selectByUserId(userId, teamType);
    }
}
